package com.doublefish.doublefishrobot.ui.home.s6;

import android.content.Context;
import android.content.Intent;
import android.view.KeyEvent;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.alibaba.fastjson.JSONArray;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.listener.OnItemClickListener;
import com.doublefish.doublefishrobot.R;
import com.doublefish.doublefishrobot.base.BaseActivity;
import com.doublefish.doublefishrobot.ui.home.adapter.ModeSectionAdapter;
import com.doublefish.doublefishrobot.ui.home.bean.ModeBean;
import com.doublefish.doublefishrobot.ui.home.bean.ModeSettingBean;
import com.doublefish.doublefishrobot.utils.ble.bean.ModeConstant;

import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * 作者:dugaofeng on 2024/10/24 10:14
 */
public class S6ModeTrainListActivity  extends BaseActivity {

    @BindView(R.id.tv_title)
    TextView titleTv;
    @BindView(R.id.recycler_mode)
    RecyclerView recyclerView;

    @BindView(R.id.et_search)
    EditText editText;
    private String lastSearchText = "";

    private ModeSectionAdapter sectionAdapter;
    private List<ModeSectionAdapter.ModeMultipleEntity> showList = new ArrayList<>();  //显示在适配器的数据
    private List<ModeSectionAdapter.ModeMultipleEntity> sysModeList = new ArrayList<>();  //系统配置的48个模式

    @Override
    protected int getLayoutId() {
        return R.layout.activity_mode_train_list;
    }

    @Override
    protected void initView() {
        titleTv.setText(getString(R.string.trainning_mode));
    }

    @Override
    protected void initListener() {
        sectionAdapter = new ModeSectionAdapter(showList);
        recyclerView.setLayoutManager(new LinearLayoutManager(this));
        recyclerView.setAdapter(sectionAdapter);
        sectionAdapter.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(@NonNull BaseQuickAdapter<?, ?> adapter, @NonNull View view, int position) {
                //选择了模式
                ModeSectionAdapter.ModeMultipleEntity modeMultipleEntity = showList.get(position);
                if (!modeMultipleEntity.isHeader()) {
                    //显示模式的详情
                    ModeSettingBean itemBean = modeMultipleEntity.getModeSettingBean();
                    if (itemBean.getMode() == 0) {
                        Intent intent = new Intent(S6ModeTrainListActivity.this, S6ModeNormalActivity.class);
                        startActivity(intent);
                    } else {
                        Intent intent = new Intent(S6ModeTrainListActivity.this, S6ModeTrainLoopActivity.class);
                        intent.putExtra("mode", itemBean);
                        startActivity(intent);
                    }
                }
            }
        });

        //键盘搜索按钮点击的监听
        editText.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView textView, int actionId, KeyEvent keyEvent) {
                if (actionId == EditorInfo.IME_ACTION_SEARCH) {
                    //回收键盘 并搜索
                    onSearchBtnClick();
                }
                return false;
            }
        });
    }

    @Override
    protected void initData() {
        //获取系统模式数据
        initSysData();
        //显示系统模式数据
        showList.addAll(sysModeList);
        sectionAdapter.setSearching(false);
        sectionAdapter.notifyDataSetChanged();    }

    //获取系统模式数据
    private void initSysData() {
        String json = readTypeFromFile();
        if (json == null || json.length() == 0) {
            return;
        }
        List<ModeBean> types = JSONArray.parseArray(json, ModeBean.class);
        if (types == null) {
            return;
        }
        for (int i = 0; i < types.size(); i++) {
            ModeBean bean = types.get(i);
            ModeSectionAdapter.ModeMultipleEntity entity = new ModeSectionAdapter.ModeMultipleEntity(true);
            entity.setModeBean(bean);
            sysModeList.add(entity);
            if (bean.getItems() == null || bean.getItems().size() == 0) {
                entity.setShowLine(i == types.size() - 1);  //分割线
                continue;
            }
            for (int j = 0; j < bean.getItems().size(); j++) {
                ModeSettingBean item = bean.getItems().get(j);
                item.setProtocolType(ModeConstant.ProtocolTypeS6);

                ModeSectionAdapter.ModeMultipleEntity child = new ModeSectionAdapter.ModeMultipleEntity(false);
                child.setModeSettingBean(item);
                if (i != types.size() - 1 && j == bean.getItems().size() - 1) {
                    child.setShowLine(false);
                }
                sysModeList.add(child);
            }
        }
    }

    //从本地Assets中读取文件 设备分类
    private String readTypeFromFile() {
        try {
            InputStream inputStream = getResources().getAssets().open("s6_mode.json");
            int length = inputStream.available();
            byte[] buff = new byte[length];
            inputStream.read(buff);
            inputStream.close();

            String json = new String(buff, StandardCharsets.UTF_8);
            return json;
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
    }

    @OnClick(R.id.ll_back)
    public void onBackClick() {
        finish();
    }



    @OnClick(R.id.tv_search)
    public void onSearchBtnClick() {
        hideKeyboard();
        refreshModeList();
    }

    private void refreshModeList() {
        String searchText = editText.getText().toString().trim();
        if (searchText.equals(lastSearchText)) {
            return;
        }
        lastSearchText = searchText;
        showList.clear();
        if (searchText.isEmpty()) {
            showList.addAll(sysModeList);
            sectionAdapter.setSearching(false);
        } else {
            for (ModeSectionAdapter.ModeMultipleEntity item : sysModeList) {
                if (!item.isHeader() && item.getModeSettingBean().getName().contains(searchText)) {
                    showList.add(item);
                }
            }
            sectionAdapter.setSearching(true);
        }
        sectionAdapter.notifyDataSetChanged();
    }

    //回收键盘
    private void hideKeyboard() {
        //回收键盘
        InputMethodManager imManager = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
        if (imManager != null && getCurrentFocus() != null) {
            imManager.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(), 0);
        }
    }
}
